package com.dejav.core;

import java.util.HashMap;
import java.util.Iterator;

import org.apache.bcel.Constants;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.BasicType;
import org.apache.bcel.generic.ClassGen;
import org.apache.bcel.generic.INVOKESTATIC;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.Type;
import org.apache.bcel.util.InstructionFinder;

import com.dejav.patterns.FilePatterns;


public class FileAnalyzer {

	final String fileName;
	HashMap<String, ClassGen> jarClasses = new HashMap<String, ClassGen>();
	
	public FileAnalyzer(String fileName) {
		this.fileName = fileName;
	}

	public void analyze(HashMap<String, ClassGen> classes) {
		this.jarClasses = classes;
		
		for(ClassGen cg : classes.values()) {
			for(Method m : cg.getMethods()) {
				
				if(!m.getName().equals("<clinit>"))
					continue;
				
				MethodGen mg = new MethodGen(m ,cg.getClassName(), cg.getConstantPool());
				InstructionList il = mg.getInstructionList();
				
				if (il == null) {
					continue;
				}
				
				InstructionFinder finder = new InstructionFinder(il);
				Iterator i = finder.search(FilePatterns.ZKM_IDENTFY);
				if(i.hasNext()) {
					InstructionHandle[] h = (InstructionHandle[]) i.next();
					String stringCall = ((INVOKESTATIC) h[4].getInstruction()).getSignature(cg.getConstantPool());
					String charCall = ((INVOKESTATIC) h[5].getInstruction()).getSignature(cg.getConstantPool());
					
					if(stringCall.equals("(Ljava/lang/String;)[C") &&
							charCall.equals("([C)Ljava/lang/String;")) {
						System.out.println("Detected ZKM String Encryption in: " + cg.getClassName());
						
						
					}
							
				}
				
			}
		}
		
	}
}
